import {
    Body,
    Controller,
    Delete,
    Get,
    HttpException,
    HttpStatus,
    Param,
    ParseUUIDPipe,
    Patch,
    Post,
} from '@nestjs/common';
import {UserService} from './user.service';
import {CreateUserDto} from './dto/create-user.dto';
import {UpdateUserDto} from './dto/update-user.dto';
import {userEntity} from "./entities/user.entity";
import {ApiOperation, ApiResponse, ApiTags} from "@nestjs/swagger";
import {AuthDto} from "./dto/auth.dto";

@ApiTags('user')
@Controller('user')
export class UserController {
    constructor(private readonly userService: UserService) {
    }

    @ApiOperation({summary: '注册用户'})
    @ApiResponse({status: 201, type: [userEntity]})
    @Post('register')
    async create(@Body() createUserDto: CreateUserDto) {
        const {email} = createUserDto;
        const existUser = await this.userService.findOneByEmail(email);
        if (existUser) {
            throw new HttpException("用户名已存在", HttpStatus.BAD_REQUEST)
        }
        return new userEntity(await this.userService.create(createUserDto));
    }

    @ApiOperation({summary: '登录'})
    @ApiResponse({status: 200, type: [userEntity]})
    @Post('login')
    async login(@Body() {email, password}: AuthDto) {
        return new userEntity(await this.userService.login(email, password));
    }

    @Get()
    async findAll() {
        const users = await this.userService.findAll();
        return users.map((user) => new userEntity(user));
    }

    @Get(':id')
    async findOne(@Param('id', ParseUUIDPipe) id: string) {
        return new userEntity(await this.userService.findOneById(id));
    }

    @Patch(':id')
    async update(
        @Param('id',ParseUUIDPipe) id: string,
        @Body() updateUserDto: UpdateUserDto
    ) {
        return new userEntity(
            await this.userService.update(id, updateUserDto)
        );
    }

    @Delete(':id')
    async remove(@Param('id',ParseUUIDPipe) id: string) {
        return new userEntity(await this.userService.remove(id));
    }
}
